#!/usr/bin/env python

import sys
import re
import gobject

class AvatarItemInitError(object):
    pass

class AvatarItem(gobject.GObject):
    def __init__(self, *vargs, **kargs):
        self.__gobject_init__()

        self.icon = None
        self.name = None
        self.grid = None
        self.url = None

        nargs = len(vargs) + len(kargs)
        names = ['name', 'grid', 'url', 'icon']

        if nargs == 1:
            self.__init_from_markup(names, vargs, kargs)
            self.icon = "avatar.png"
        elif nargs == 3:
            self.__init_impl(names, vargs, kargs)
            self.icon = "avatar.png"
        elif nargs == 4:
            self.__init_impl(names, vargs, kargs)
        
        for n in names:
            if getattr(self, n) == None:
                raise AvatarItemInitError

    def __init_impl(self, names, vargs, kargs):
        for i, v in enumerate(vargs): setattr(self, names[i], v)
        for k, v in kargs: setattr(self, k, v)

    def __init_from_markup(self, names, vargs, kargs):
        markup = kargs['markup'] if 'markup' in kargs else vargs[0]
        args = re.sub(r'<[^>]*>([^<]*)<\/[^>]*>', r'\1', markup).split('\n')
        self.__init_impl(names,args,kargs)
        
    def get_markup(self):
        return "<big>"+ \
                gobject.markup_escape_text(self.name) +"</big>\n<i>"+ \
                gobject.markup_escape_text(self.grid) +"</i>\n<small>"+ \
                gobject.markup_escape_text(self.url) +"</small>"


def load(filename):
    table = {}
    file = open(filename,'r')
    try:
        lines = file.readlines()
        for line in lines:
            data = line.strip().split(',')
            table[data[0]] = data
    finally:
        file.close()

    return table

def load_avatars(filename, avatars):
    table = load(filename)
    avatars += [AvatarItem(*item) for item in table.values()]
